<?php
session_start();
if(isset($_SESSION['admin_id'])) {
    include "../include/dbFunctions.php";
    if(isset($_GET['id'])) {
        $id = $_GET['id'];
        $select="SELECT * FROM program p, event e
            WHERE p.program_id=e.program_id
            AND program_id=$id";
        $numevent=executeSelectQuery($select);
        $eventresult=count($numevent);
        if( $eventresult==0){
            $eQuery = "DELETE FROM program_education WHERE program_id = '".$id."'";
            $eresult = executeQuery($eQuery);
            $sQuery = "DELETE FROM program WHERE program_id = '".$id."'";
            $result = executeQuery($sQuery);
            if ($result!=0&&$eresult!=0) {
                $_SESSION['mes'] = "Your record has been deleted successfully";
            } else {
                $_SESSION['mes'] = "Error! Please try again";
            }
            header('Location: programManage.php');
        }else{
             $_SESSION['mes'] = "Cannot delete program because there are related events. ";
             header('Location: programManage.php');
        }

    }elseif(isset($_POST['id_program'])) {
        $id_program=$_POST['id_program'];
        $arr_num=count($id_program);
        $i=0;
        $select="SELECT * FROM program p, event e
            WHERE p.program_id=e.program_id
            AND program_id=$id_program";
        $numevent=executeSelectQuery($select);
        $eventresult=count($numevent);
        if( $eventresult==0){
            while ($i < $arr_num) {
            $eQuery="DELETE FROM program_education WHERE program_id = '".$id_program[$i]."'";
            $eResult = executeQuery($eQuery);
            $uQuery= "DELETE FROM program
            WHERE program_id='".$id_program[$i]."'";
                $uResult = executeQuery($uQuery);
                $i++;
            }
            if (($uResult!=0)&&($eResult!=0)) {
                $_SESSION['mes'] = "Your record has been deleted successfully";
            }else {
                $_SESSION['mes'] = "Error! Please try again";
            }
            header('Location: programManage.php');
        }else{
             $_SESSION['mes'] = "Cannot delete program because there are related events. ";
             header('Location: programManage.php');
        }

    }else{
        $_SESSION['mes'] = "You must choose at least 1 record to delete.";
    header('Location: programManage.php');
    }

}else {
    header("Location: ../include/login.html");
}
?>